package com.gs.synedocket.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gs.synedocket.R;
import com.gs.synedocket.activity.base.BaseFragmentActivity;
import com.gs.synedocket.adapter.MenuListAdapter;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.constant.HandleCode;
import com.gs.synedocket.constant.SyncStatus;
import com.gs.synedocket.control.CircleImageView;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.DriverSignDto;
import com.gs.synedocket.db.dto.MenuDto;
import com.gs.synedocket.db.dto.UserDto;
import com.gs.synedocket.db.dto.VersionDto;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.dialog.CommDialogUtils;
import com.gs.synedocket.dialog.DialogUtil;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.SureDialog;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.dialog.VersionDialog;
import com.gs.synedocket.fragment.DocketListFragment;
import com.gs.synedocket.fragment.DocketLogFragment;
import com.gs.synedocket.fragment.DocketOnHandFragment;
import com.gs.synedocket.fragment.ScanPaperFragment;
import com.gs.synedocket.fragment.SettingFragment;
import com.gs.synedocket.fragment.TruckChangeFragment;
import com.gs.synedocket.presenter.MainPresenter;
import com.gs.synedocket.receiver.NetworkBroadcastReceiver;
import com.gs.synedocket.service.CloseService;
import com.gs.synedocket.service.GpsService;
import com.gs.synedocket.service.LogService;
import com.gs.synedocket.util.ActivityUtil;
import com.gs.synedocket.util.AppUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.GsonUtil;
import com.gs.synedocket.util.ImageUtil;
import com.gs.synedocket.util.MyHandler;
import com.gs.synedocket.util.NetworkUtil;
import com.gs.synedocket.util.OKHttpUtil;
import com.gs.synedocket.util.PermissionUtil;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.util.SyncDownloadUtil;
import com.gs.synedocket.util.SyncTableUtil;
import com.gs.synedocket.util.SyncUploadUtil;
import com.gs.synedocket.util.ThreadManager;
import com.gs.synedocket.util.ToastUtil;
import com.gs.synedocket.view.IMainView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseFragmentActivity implements IMainView {

    private final String PID = "C081F0C8-BEC5-4F3B-86E6-A28BF5068286";
    private DrawerLayout drawerLayout;
    private List<Fragment> fragmentList;
    private List<String> fragmentTag;
    private Fragment mFragment;
    private int fragmentIndex;
    private MainPresenter mPresenter;
    private MenuListAdapter adapter;
    private ArrayList<MenuDto> list;
    private TextView tvTel, tvSite, tvTruck, tvNewVersion;
    private UserDto userDto;
    private ImageView ivLogo;
    private boolean canBack, isShowDialog, isLang;
    private Intent logService;
    private DriverSignDto mBean;
    private SureDialog sureDialog, exitSureDialog;
    private VersionDialog versionDialog;
    private NetworkBroadcastReceiver receiver;
    private MyHandler myHandler;

    private void showLoading(int tip) {
        LoadingDialogUtils.getInstance().showLoading(this, getString(tip));
        LoadingDialogUtils.getInstance().setCancelable(false);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        myHandler = new MyHandler(Looper.getMainLooper(), this);
        PermissionUtil.addPermission(this, new String[]{
                Manifest.permission.REQUEST_INSTALL_PACKAGES,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_PHONE_STATE}, 1);
        ivLogo = fd(R.id.iv_logo);
        tvTel = fd(R.id.tv_tel);
        tvSite = fd(R.id.tv_site);
        tvTruck = fd(R.id.tv_truck);
        tvNewVersion = fd(R.id.tv_version);
        setVersion();
        setUserInfo();
        drawerLayout = fd(R.id.drawerLayout);
        drawerLayout.openDrawer(GravityCompat.START);
        drawerLayout.addDrawerListener(new MyDrawerListener());
        list = new ArrayList<>();
        RecyclerView recyclerView = fd(R.id.rv_menu);
        adapter = new MenuListAdapter(this, list, R.layout.rvitem_main_menu);
        adapter.setOnItemClickListener((v, position) -> adapterOnItemClick(position));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        mPresenter = new MainPresenter();
        mPresenter.attachView(this);
        registerReceiver();
        MyOnClickListener myOnClickListener = new MyOnClickListener();
        fd(R.id.iv_menu).setOnClickListener(myOnClickListener);
        ivLogo.setOnClickListener(myOnClickListener);
        tvNewVersion.setOnClickListener(myOnClickListener);
        fd(R.id.llTab).setOnLongClickListener(new MyOnLongClickListener());
        isShowDialog = true;
        // 切换语言
        if (savedInstanceState != null) {
            isLang = true;
            fragmentIndex = savedInstanceState.getInt(AllConstants.WHAT);
            showFragment(mFragment, getFragment(), getFragmentTag());
            tvTruck.setText(SPUtil.getInstance().getString(AllConstants.TRUCK_NAME));
            tvTel.setVisibility(View.GONE);
            mPresenter.getList(PID);
            return;
        }
        int what = getIntent().getIntExtra(AllConstants.WHAT, 0);
        if (what == HandleCode.MSG_LOGIN) {// 第一次登陆
            myHandler.setLogin(true);
            syncUpload();
        } else {
            mPresenter.getList(PID);
            if (what == HandleCode.MSG_SHOW_NOTIFICATION) { // 点击通知跳转
                LogUtil.getInstance().insertOrReplaceData("點擊推送通知");
                fragmentIndex = 1;
                myHandler.setNotifyClick(true);
                adapter.changeSelect(fragmentIndex);
                drawerLayout.closeDrawer(GravityCompat.START);
                if (SyncStatus.isSync()) {
//                if (SyncDownloadUtil.getInstance().isDownload()) {
                    showFragment(mFragment, getFragment(), getFragmentTag());
                } else {
                    syncUpload();
                }
                return;
            } else if (what == HandleCode.MSG_WARNING) { // 长时间休眠
                showWarning();
            }
        }
        if (fragmentIndex == 0) {
            mPresenter.getVersion();
            logService = new Intent(this, LogService.class);
            startService(logService);
            startService(new Intent(this, CloseService.class));
        }
    }

    class MyDrawerListener implements DrawerLayout.DrawerListener {

        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {
            if (DocketUtil.getInstance().getUpgradeLevel() == AllConstants.UPGRADE_FIRST) {
                drawerLayout.openDrawer(GravityCompat.START);
                ToastUtil.showToast(R.string.upgrade_first);
                LogUtil.getInstance().insertOrReplaceData(getString(R.string.upgrade_log, AppUtil.getInstance().getVersion()));
            }
        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    }

    private void adapterOnItemClick(int position) {
        try {
            if (DocketUtil.getInstance().getUpgradeLevel() == AllConstants.UPGRADE_FIRST) {
                ToastUtil.showToast(R.string.upgrade_first);
                LogUtil.getInstance().insertOrReplaceData(getString(R.string.upgrade_log, AppUtil.getInstance().getVersion()));
                return;
            }
            if (list == null) return;
            MenuDto menu = list.get(position);
            if (menu == null || menu.getUrl() == null) {
                ToastDialogUtils.getInstance().showInfoMessage(MainActivity.this, R.string.no_window);
                return;
            }
            // 登出
            if (menu.getUrl().equals("exitSysAct") && (menu.getOperFlag() != null && menu.getOperFlag() == 1)) {
                exit();
            } else {
                LogUtil.getInstance().insertOrReplaceData("查看-" + menu.getName());
                String url = menu.getUrl().replace("Act", "Fragment").toLowerCase();
                for (int i = 0; i <= fragmentTag.size() - 1; i++) {
                    if (fragmentTag.get(i).toLowerCase().equals(url)) {
                        fragmentIndex = i;
                        break;
                    }
                }
                if (fragmentIndex == 0) { // DocketOnHandFragment
                    // 從查看docket Log詳情轉換到查看處理Docket單
                    if (DocketUtil.getInstance().isLogDetail()) {
                        DocketUtil.getInstance().setDocketId("");
                        DocketUtil.getInstance().setLogDetail(false);
                        EventBus.getDefault().post(new Event(EventCode.EVENT_RETURN_DOCKET));
                    } else {
                        setTopTv();
                    }
                } else {
                    tvTruck.setText(SPUtil.getInstance().getString(AllConstants.TRUCK_NAME));
                    setLogo();
                    tvTel.setVisibility(View.GONE);
                    tvSite.setText(list.get(position).getName());
                }
                showFragment(mFragment, getFragment(), getFragmentTag());
            }
            adapter.changeSelect(position);
            drawerLayout.closeDrawer(GravityCompat.START);
        } catch (Exception e) {
            e.printStackTrace();
            ToastDialogUtils.getInstance().showInfoMessage(MainActivity.this, R.string.no_window);
        }
    }

    /**
     * 登出
     */
    private void exit() {
        // 先上傳數據
        if (!SyncStatus.isSync() && NetworkUtil.getInstance().getNetworkSignal()) {
//        if (!SyncUploadUtil.getInstance().isUpload() && NetworkUtil.getInstance().getNetworkSignal()) {
            myHandler.setLogout(true);
            syncUpload();
        }
        if (exitSureDialog == null) {
            exitSureDialog = new SureDialog(MainActivity.this, R.string.logout, () -> {
                if (DocketUtil.getInstance().getUpgradeLevel() == AllConstants.UPGRADE_FIRST) {
                    ToastUtil.showToast(R.string.upgrade_first);
                    LogUtil.getInstance().insertOrReplaceData(getString(R.string.upgrade_log, AppUtil.getInstance().getVersion()));
                    return;
                }
                if (SyncStatus.isSync()) {
//                if (SyncUploadUtil.getInstance().isUpload() || SyncDownloadUtil.getInstance().isDownload()) {
                    myHandler.setAutoLogout(true);
                    showLoading(R.string.auto_sync_ing);
                    return;
                }
                mPresenter.logOut();
            });
            exitSureDialog.setOnDismissListener(dialog -> {
                // 修改recyclerview選擇
                if (ActivityUtil.getInstance().isSurvive(MainActivity.this) && mFragment != null) {
                    adapter.changeSelect(fragmentIndex);
                }
            });
        }
        exitSureDialog.show();
    }

    private void setUserInfo() {
        String str = SPUtil.getInstance().getString(AllConstants.LOGIN_INFO);
        if (!TextUtils.isEmpty(str)) {
            TextView tvName = fd(R.id.tv_name);
            CircleImageView iv = fd(R.id.iv_add_photo);
            userDto = (UserDto) GsonUtil.getInstance().fromJson(str, UserDto.class);
            tvName.setText(userDto.getUserName() == null ? "" : userDto.getUserName());
            if (TextUtils.isEmpty(userDto.getPhoto())) {
                iv.setImageResource(R.mipmap.default_person);
            } else {
                ImageUtil.loadImg(this, OKHttpUtil.IMG_URL + userDto.getPhoto(), iv, R.mipmap.default_person);
            }
        }
    }

    /**
     * 上传本地数据
     */
    private void syncUpload() {
        new Thread(() -> {
            SyncUploadUtil.getInstance().setOnSyncListener(this::sendMsg);
            SyncUploadUtil.getInstance().upload();
        }).start();
    }

    /**
     * 修改头部tab
     */
    private void setTopTv() {
        tvSite.setText(DocketUtil.getInstance().getDocketSite());
        String docketNo1 = DocketUtil.getInstance().getDocketNo();
        tvTel.setText(docketNo1 == null ? "" : docketNo1.trim());
        tvTel.setVisibility(View.VISIBLE);
        String truckNo = DocketUtil.getInstance().getTruckNo();
        tvTruck.setText(TextUtils.isEmpty(truckNo) ? SPUtil.getInstance().getString(AllConstants.TRUCK_NAME) : truckNo);
    }

    private void setVersion() {
        setVersion(String.format("V%s", AppUtil.getInstance().getVersion()), R.color.color_999);
    }

    private void setVersion(String text, int color) {
        tvNewVersion.setText(text);
        tvNewVersion.setTextColor(getResources().getColor(color));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SyncStatus.setSync(false);
//        SyncUploadUtil.getInstance().setUpload(false);
//        SyncDownloadUtil.getInstance().setDownload(false);
        if (logService != null) {
            stopService(logService);
            logService = null;
        }
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        DialogUtil.getInstance().dialogDestroy(new Dialog[]{versionDialog, sureDialog, exitSureDialog});
        hideLoading();
        ToastDialogUtils.getInstance().dismiss();
        stopService(new Intent(this, GpsService.class));
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    protected void initFragment() {
        fragmentList = new ArrayList<>();
        fragmentTag = new ArrayList<>();
        fragmentList.add(new DocketOnHandFragment());
        fragmentList.add(new DocketListFragment());
        fragmentList.add(new DocketLogFragment());
        fragmentList.add(new ScanPaperFragment());
        fragmentList.add(new TruckChangeFragment());
        fragmentList.add(new SettingFragment());
        fragmentTag.add(DocketOnHandFragment.class.getSimpleName());
        fragmentTag.add(DocketListFragment.class.getSimpleName());
        fragmentTag.add(DocketLogFragment.class.getSimpleName());
        fragmentTag.add(ScanPaperFragment.class.getSimpleName());
        fragmentTag.add(TruckChangeFragment.class.getSimpleName());
        fragmentTag.add(SettingFragment.class.getSimpleName());
    }

    private Fragment getFragment() {
        return fragmentList.get(fragmentIndex);
    }

    private String getFragmentTag() {
        return fragmentTag.get(fragmentIndex);
    }

    private void showFragment(Fragment fromFragment, Fragment toFragment, String tag) {
        if (fromFragment != toFragment) {
            mFragment = toFragment;
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            if (fromFragment != null) {
                transaction.hide(fromFragment);
            }
            if (toFragment.isAdded()) {
                transaction.show(toFragment);
            } else {
                transaction.add(R.id.fl_content, toFragment, tag);
            }
            transaction.commitAllowingStateLoss();
//            transaction.commit();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(AllConstants.WHAT, fragmentIndex);
    }

    /**
     * 刷新時清除舊的fragment
     */
    @Override
    public void recreate() {
        try {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            for (Fragment fragment : fragmentList) {
                ft.detach(fragment);
            }
            ft.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.recreate();
    }

    @Override
    protected void event(Event event) {
        switch (event.getWhat()) {
            case EventCode.EVENT_LOGOUT:
                mPresenter.logOut();
                break;
            case EventCode.EVENT_SHOW_FRAGMENT:
                showFragment(mFragment, getFragment(), getFragmentTag());
                break;
            case EventCode.EVENT_SHOW_MENU:
                mPresenter.getList(PID);
                break;
            case EventCode.EVENT_REFRESH_DOWNLOAD: // 在ON HAND下拉刷新或者完成一个docket后需先上传数据后下载docket onHandList数据
                myHandler.setRefreshDownload(true);
//                if (NetworkUtil.getInstance().getNetworkSignal() && !SyncDownloadUtil.getInstance().isDownload() && !SyncUploadUtil.getInstance().isUpload()) {
                if (NetworkUtil.getInstance().getNetworkSignal() && !SyncStatus.isSync()) {
                    syncUpload();
                }
                break;
            case EventCode.EVENT_LIST_REFRESH_DOWNLOAD: // 在Docket List下拉刷新时需先上传数据后下载docket onHandList数据
                myHandler.setRefreshListDownload(true);
//                if (NetworkUtil.getInstance().getNetworkSignal() && !SyncDownloadUtil.getInstance().isDownload() && !SyncUploadUtil.getInstance().isUpload()) {
                if (NetworkUtil.getInstance().getNetworkSignal() && !SyncStatus.isSync()) {
                    syncUpload();
                }
                break;
            case EventCode.EVENT_LOG_REFRESH_DOWNLOAD: // 在Docket Log List下拉刷新时需先上传数据后下载docket deliveryLogList数据
                myHandler.setRefreshLogDownload(true);
//                if (NetworkUtil.getInstance().getNetworkSignal() && !SyncDownloadUtil.getInstance().isDownload() && !SyncUploadUtil.getInstance().isUpload()) {
                if (NetworkUtil.getInstance().getNetworkSignal() && !SyncStatus.isSync()) {
                    syncUpload();
                }
                break;
            case EventCode.EVENT_AUTO_UPLOAD:// 同步上傳信息
                if (event.getAutoState() == 0) return;
                myHandler.setAuto(true);
                sendMsg(event.getAutoState(), event.getMsg());
                break;
            case EventCode.EVENT_AUTO_DOWNLOAD:// 同步下載信息
                if (event.getAutoState() == 0) return;
                myHandler.setAutoDownload(true);
                sendMsg(event.getAutoState(), event.getMsg());
                break;
            case EventCode.EVENT_ON_HAND:// 在docket List点击单个docket时跳转到ON HAND
                fragmentIndex = 0;
                showFragment(mFragment, getFragment(), getFragmentTag());
                adapter.changeSelect(0);
                String docketNo = DocketUtil.getInstance().getDocketNo();
                tvTel.setText(docketNo == null ? "" : docketNo.trim());
                tvTel.setVisibility(View.VISIBLE);
                if (userDto.getSite() != null) {
                    tvSite.setText(userDto.getSite().getName());
                } else {
                    tvSite.setText("");
                }
                break;
            case EventCode.EVENT_LOG_DETAIL:// 在docket log点击单个docket时跳转到ON HAND
                fragmentIndex = 0;
                showFragment(mFragment, getFragment(), getFragmentTag());
                break;
            case EventCode.EVENT_TRUCK:// 切换Truck
                tvTruck.setText(SPUtil.getInstance().getString(AllConstants.TRUCK_NAME));
                break;
            case EventCode.EVENT_DONE_ON_HAND: // 查看当前的docket
                if (!event.getState()) {
                    setTopTv();
                }
                break;
            case EventCode.EVENT_ARRIVE_SITE:
            case EventCode.EVENT_OK:
            case EventCode.EVENT_ADDITIONAL:
            case EventCode.EVENT_SHOW_REVERT_SIGN:// 显示可回退状态按钮
                if (!canBack) {
                    ivLogo.setImageResource(R.drawable.ic_back);
                    canBack = true;
                }
                break;
            case EventCode.EVENT_HIDE_REVERT_SIGN:
            case EventCode.EVENT_DONE_QC_CHECK: // 隐藏可回退状态按钮
                setLogo();
                break;
        }
    }

    private void sendMsg(int status, String msg) {
        Message message = Message.obtain();
        message.what = status;
        message.obj = msg;
        myHandler.sendMessage(message);
    }

    private void setLogo() {
        if (canBack) {
            ivLogo.setImageResource(R.drawable.logo);
            canBack = false;
        }
    }

    @Override
    public void onGetListSuccess(ApiResultData<List<MenuDto>> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResult.getMessage());
            return;
        }
        list.clear();
        list.addAll(apiResult.getData());
        if (list.isEmpty()) {
            SyncStatus.setSync(true);
//            SyncUploadUtil.getInstance().setUpload(true);
            showLoading(R.string.auto_download);
            downloadSysTable();
            return;
        }
        if (isLang) {
            list.get(fragmentIndex).setSelect(true);
            drawerLayout.closeDrawer(GravityCompat.START);
            tvSite.setText(list.get(fragmentIndex).getName());
            isLang = false;
        } else {
            if (fragmentIndex != 0) {
                list.get(fragmentIndex).setSelect(true);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onGetListFails(Exception msg) {
        ToastDialogUtils.getInstance().showInfoMessage(this, R.string.network_error);
    }

    /**
     * 当用户在第一次登陆时没等待下载成功后就退出app，重新进入app时重新下载系统表
     */
    private void downloadSysTable() {
        ThreadManager.getInstance().execute(() -> {
            // 先清空旧数据表
            DBApi.getInstance().deleteSysTable();
            SyncTableUtil.getInstance().setOnSyncListener(this::sendMsg);
            SyncTableUtil.getInstance().download();
        });
    }

    @Override
    public void onLogoutSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResult.getMessage());
            return;
        }
        LogUtil.getInstance().insertOrReplaceData(apiResult.getMessage());
        DBApi.getInstance().deleteUserTruckTable();
        ActivityUtil.getInstance().finishActivity(this);
    }

    @Override
    public void onLogoutFails(Exception msg) {
        ToastDialogUtils.getInstance().showInfoMessage(this, R.string.network_error);
    }

    @Override
    public void onRevertSuccess(ApiResultData<String> apiResult, int newState) {
        ToastDialogUtils.getInstance().showInfoMessage(this, apiResult.getMessage());
        if (apiResult.getStatus() != 2000) {
            return;
        }
        LogUtil.getInstance().insertOrReplaceData(DocketUtil.getInstance().getDocketNo() + "-回退狀態成功");
        // 修改当前操作docket的状态
        DocketUtil.getInstance().setTruckState(newState);
        DBApi.getInstance().updateDocketTruckState(DocketUtil.getInstance().getDocketId(), newState);
        mBean = null;
        setLogo();
        EventBus.getDefault().post(new Event(EventCode.EVENT_DONE_REVERT_SIGN));
    }

    @Override
    public void onRevertFails(Exception msg) {
        ToastDialogUtils.getInstance().showInfoMessage(this, R.string.network_error);
    }

    @Override
    public void onGetVersionSuccess(ApiResultData<VersionDto> apiResultData) {
        tvNewVersion.setEnabled(true);
        if (SPUtil.getInstance().getString(AllConstants.ID).isEmpty()) {
            return;
        }
        VersionDto data = apiResultData.getData();
        if (apiResultData.getStatus() == 2000 && data != null) {
            int newVersion;
            int myVersion;
            try {
                newVersion = Integer.parseInt(data.getVersion().replace(".", ""));
                myVersion = Integer.parseInt(AppUtil.getInstance().getVersion().replace(".", ""));
            } catch (NumberFormatException e) {
                ToastUtil.showToast(R.string.version_error);
                e.printStackTrace();
                return;
            }
            if (newVersion > myVersion) {
                DocketUtil.getInstance().setUpgradeLevel(data.getUpgradeLevel());
                LogUtil.getInstance().insertOrReplaceData("獲取APP新版本" + data.getVersion());
                setVersion(getString(R.string.new_version1, data.getVersion()), R.color.red);
                if (isShowDialog) {
                    if (versionDialog == null) {
                        versionDialog = new VersionDialog(MainActivity.this, data.getDesc(), (buttonId) -> {
                            String fileName = data.getOutputFile();
                            File file = new File(MainActivity.this.getCacheDir(), fileName);
                            if (file.exists()) file.delete();// 已下載過安裝包
                            else file.getParentFile().mkdirs();
                            // 展示進度條
                            CommDialogUtils.showProgressDialog(MainActivity.this);
                            if (buttonId == R.id.rb_server1) {  // 单线程下载
                                mPresenter.downloadFile(fileName, file);
                            } else { // 多线程下载
                                mPresenter.downloadFileMulti(fileName, file);
                            }
                        });
                    }
                    versionDialog.show();
                }
                return;
            }
        }
        setVersion();
    }

    @Override
    public void onGetVersionFails(Exception e) {
        tvNewVersion.setEnabled(true);
    }

    @Override
    public void onDownloadFileSuccess(File file) {
        AppUtil.getInstance().installApk(MainActivity.this, file);
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void onDownloadProgress(int progress) {
        CommDialogUtils.setProgress(progress);
    }

    @Override
    public void onDownloadFails(Exception e) {
        ToastUtil.showToast(R.string.download_error);
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnLongClickListener implements View.OnLongClickListener {

        @Override
        public boolean onLongClick(View v) {
            exit();
            return true;
        }
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.iv_menu) {
                if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                    drawerLayout.closeDrawer(GravityCompat.START);
                } else {
                    isShowDialog = false;
                    mPresenter.getVersion();
                    drawerLayout.openDrawer(GravityCompat.START);
                    if (list.isEmpty()) {
                        mPresenter.getList(PID);
                    }
                }
            } else if (id == R.id.iv_logo) { // 回退状态
                if (canBack) {
                    if (sureDialog == null) {
                        sureDialog = new SureDialog(MainActivity.this, R.string.back_status,
                                () -> resetState(DocketUtil.getInstance().getTruckState() - 1));
                    }
                    sureDialog.show();
                }
            } else if (id == R.id.tv_version) {
                v.setEnabled(false);
                isShowDialog = true;
                mPresenter.getVersion();
            }
        }
    }

    /**
     * 重设当前docket状态
     */
    private void resetState(int newState) {
        mBean = new DriverSignDto();
        mBean.setDocketId(DocketUtil.getInstance().getDocketId());
        mBean.setState(newState);
        mPresenter.revertSign(mBean, newState);
    }

    /**
     * 监听网络变化广播
     */
    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        receiver = new NetworkBroadcastReceiver();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (getSupportFragmentManager().findFragmentByTag(getFragmentTag()) != null) {
            getSupportFragmentManager().findFragmentByTag(getFragmentTag()).onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (getSupportFragmentManager().findFragmentByTag(getFragmentTag()) != null) {
            getSupportFragmentManager().findFragmentByTag(getFragmentTag()).onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) super.onBackPressed();
        else drawerLayout.openDrawer(GravityCompat.START);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN
                && getSupportFragmentManager().getBackStackEntryCount() == 0) {
            if (drawerLayout.isDrawerOpen(GravityCompat.START)) moveTaskToBack(true);
            else drawerLayout.openDrawer(GravityCompat.START);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}